import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import Tab from './../common/TabVertical'
import Content from '../common/Content'
import Page from '../common/Page'
import Empty from '../common/Empty'
import styles from './Viewpoint.module.scss'
import api from './../../serve/api'
import { withRouter } from 'react-router-dom'

class Viewpoint extends Component {

  constructor(props) {
    super(props)
    this.state = {
      types: [],
      viewpoints: [],
      typeId: '',
      pageTotal: '',
      page: 1,
      pageSize: 15,
      selected: 0
    }
  }
  
  onTab(item, index) {
    this.setState({
      selected: index,
      typeId: item.id
    })
    this.getViewpoint(item.id, 1)
  }

  getCurrentPage(currentPage) {
    this.getViewpoint(this.state.typeId, currentPage)
  }

  componentDidMount() {
    this.getViewpointTypeAll()
  }

  async getViewpointTypeAll() {
    const data = await api.listViewpointTypeApi()
    if (data && data.code === '000000') {
      this.setState({
        types: data.result
      })
      if (data.result.length > 0) {
        const first = data.result[0]
        this.getViewpoint(first.id, this.state.page)
      }
    }
  }

  async getViewpoint(typeId, page) {
    const data = await api.listViewpointApi({ typeId, page, pageSize: this.state.pageSize })
    if (data && data.code === '000000') {
      this.setState({
        page,
        typeId,
        viewpoints: data.result || [],
        pageTotal: data.resultNum
      })
    }
  }

  onItem(item) {
    this.props.history.push(`/mainPage/commonDetail/viewpoint/${item.id}`)
  }

  render() {
    const { types, viewpoints, page, pageTotal, selected } = this.state
    return (
      <div className={styles.viewpoint_container}>
        <div className={styles.crumbs}>
          <div className={styles.postion_div}>
            当前位置: <Link to={'/mainPage/main'}>首页</Link> > 学者观点> <span>列表</span>
          </div>
        </div>
        <div className={styles.viewpoint_content_container}>
          <Tab tabs={types} selected={selected} onTab={(item, index) => this.onTab(item, index)} />
          <div className={styles.viewpoint_content}>
            {viewpoints.length === 0 && <Empty title="暂无数据" />}
            {viewpoints.length > 0 && <Content datas={viewpoints} onItem={item => this.onItem(item)} />}
            {viewpoints.length > 0 && <Page 
              pageConfig={{totalPage: pageTotal, pageSize: this.state.pageSize, currentPage: page }}
              pageCallbackFn={currentPage => this.getCurrentPage(currentPage)}
            />}
          </div>
        </div>
      </div>
    )
  }
}

export default withRouter(Viewpoint)